package com.demo.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.constant.Constant;
import com.demo.entity.Message;
import com.demo.entity.User;
import com.demo.entity.Vo.UserVo;
import com.demo.enums.MessageRankEnum;
import com.demo.mapper.DepartmentMapper;
import com.demo.mapper.UserMapper;
import com.demo.response.Result;
import com.demo.service.IRoleService;
import com.demo.service.IUserService;
import com.demo.util.HeatUtil;
import com.demo.util.TimeUtil;
import com.demo.websocket.MyClientSocket;
import com.demo.websocket.WebSocketServer;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 用户信息表 服务实现类
 *
 * @author ZM
 * @since 2020-11-23
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    UserMapper userMapper;
    @Autowired
    IRoleService roleService;
    @Autowired
    MyClientSocket myClientSocket;
    @Resource
    DepartmentMapper departmentMapper;
    @Autowired
    WebSocketServer webSocketServer;

    /**
     * 新增用户
     *
     * @param user 实体对象
     * @return
     */
    @Override
    public Result addUser(User user) throws Exception {
        //用户登录名称与工号不得重复
        User userLoginName = userMapper.getLoginName(user.getUserLoginName());
        if (userLoginName != null) {
            throw new Exception("此登录用户名已存在");
        }
        User userWorkSn = userMapper.getWork(user.getWorkSn());
        if (userWorkSn != null) {
            throw new Exception("工号已存在");
        }
        if (user.getUserDepartment().isEmpty()) {
            throw new Exception("用户的部门不能为空");
        }
        user.setUserPass(HeatUtil.md5("123456vte"));
        save(user);
        return Result.success();
    }

    /**
     * 更新用户
     *
     * @param user 实体对象
     * @return
     */
    @Override
    public Result updateUser(User user) throws Exception {
        log.info("用户信息---" + user);
        if (user.getUserId() == null || user.getUpdatedUserId() == null) {
            return Result.error(Constant.KEY_ID);
        }

        //用户登录名称与工号不得重复
        if (user.getUserLoginName() != null) {
            User userLoginName = userMapper.getLoginName(user.getUserLoginName());
            if (userLoginName != null) {
                if (!user.getUserId().equals(userLoginName.getUserId())) {
                    throw new Exception("此登录用户名已存在");
                }
            }
        }
        if (user.getWorkSn() != null) {
            User userWorkSn = userMapper.getWork(user.getWorkSn());
            if (userWorkSn != null) {
                if (!user.getUserId().equals(userWorkSn.getUserId())) {
                    throw new Exception("工号已存在");
                }
            }
        }
        if (user.getUserDepartment().isEmpty()) {
            throw new Exception("用户的部门不能为空");
        }

        //密码不为空，执行的是修改密码
        if (!StrUtil.isEmpty(user.getUserPass())) {
            user.setUserPass(HeatUtil.md5(user.getUserPass()));
        }
        user.setUpdatedTime(new Date());
        boolean b = updateById(user);
        if (b) {
            //发送消息
            try {
                Message message = new Message();
                message.setMessageRank(MessageRankEnum.OFF_LINE.getValue());
                webSocketServer.sendToUser2(message, Arrays.asList(String.valueOf(user.getUserId())));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Result.success();


    }

    /**
     * 删除用户
     *
     * @param userId        用户ID
     * @param deletedUserId 删除人ID
     * @return
     */
    @Override
    public Result deleteUser(Integer userId, Integer deletedUserId) {
        User user = new User();
        user.setUserId(userId);
        user.setDeletedUserId(deletedUserId);
        user.setDeletedTime(new Date());
        boolean flag = updateById(user);
        if (flag == false) {
            return Result.error(Constant.DB_ERROR);
        }
        return Result.success();
    }

    /**
     * 用户列表
     *
     * @param pageNumber    页码
     * @param pageSzie      每页数量
     * @param userId        用户ID
     * @param userLoginName 用户登录名称
     * @param userTrueName  用户真实姓名
     * @param roleId        用户角色ID
     * @param userType      用户类型
     * @param userMobile    用户联系方式
     * @param workSn        工号
     * @param workStatus    工作状态
     * @return
     */
    @Override
    public Result userList(Integer pageNumber, Integer pageSzie, Integer userId, String userLoginName, String userTrueName, Integer roleId,
                           Integer userType, String userMobile, String workSn, Integer workStatus) {
        Page page = new Page(pageNumber.intValue(), pageSzie.intValue());
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq((userId != null), "user_id", userId);
        queryWrapper.eq(TimeUtil.isString(userLoginName), "user_login_name", userLoginName);
        queryWrapper.like(TimeUtil.isString(userTrueName), "user_true_name", userTrueName);
        queryWrapper.eq((roleId != null), "role_id", roleId);
        queryWrapper.eq((userType != null), "user_type", userType);
        queryWrapper.eq(TimeUtil.isString(userMobile), "user_mobile", userMobile);
        queryWrapper.eq(TimeUtil.isString(workSn), "work_sn", workSn);
        queryWrapper.eq((workStatus != null), "work_status", workStatus);
        queryWrapper.isNull("deleted_user_id");
        queryWrapper.select(new String[]{
                "user_id", "role_id", "user_login_name", "user_department", "remind", "warn", "work_status", "user_true_name", "user_mobile", "work_sn",
                "user_type", "created_time"});
        queryWrapper.orderByDesc("user_id");
        IPage iPage = userMapper.selectPage(page, queryWrapper);
        List<User> list = iPage.getRecords();
        try {
            List<UserVo> userVoList = new ArrayList<>();
            if (list.size() != 0)
                for (User user : list) {
                    UserVo userVo = new UserVo();
                    BeanUtils.copyProperties(user, userVo);
                    userVo.setRoleName(roleService.getRoleNameById(user.getRoleId()));
                    String deptNameList = "";
                    String deptNoList = user.getUserDepartment();
                    userVo.setUserDepartment(deptNoList);
                    int i = 0;
                    for (String item : deptNoList.split(",")) {
                        String deptName = departmentMapper.getDeptName(Integer.valueOf(Integer.parseInt(item)));
                        if (deptName != null) {
                            if (i == 0) {
                                deptNameList = departmentMapper.getDeptName(Integer.valueOf(Integer.parseInt(item)));
                            } else {
                                deptNameList = deptNameList + "," + departmentMapper.getDeptName(Integer.valueOf(Integer.parseInt(item)));
                            }
                            i++;
                        }
                    }
                    userVo.setUserDepartmentName(deptNameList);
                    userVoList.add(userVo);
                }
            PageInfo<UserVo> pageInfo = new PageInfo(userVoList);
            pageInfo.setTotal(iPage.getTotal());
            pageInfo.setPages((int) iPage.getPages());
            if (pageNumber.equals(Long.valueOf(iPage.getPages()))) {
                pageInfo.setIsLastPage(false);
            } else {
                pageInfo.setIsLastPage(true);
            }
            return Result.success(pageInfo);
        } catch (Exception e) {
            log.error("获取用户列表错误", e);
            return Result.fail("错误：" + e.getMessage());
        }
    }

    /**
     * 通过用户ID，获取用户（只返回名称）
     *
     * @param uid
     * @return
     */
    @Override
    public String getUnameById(Integer uid) {
        return userMapper.getUnameById(uid);
    }

}
